package com.app.dao.impl;

import java.util.Collection;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.app.dao.ProductDao;
import com.app.entity.Product;

@Repository
public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	public void deleteProduct(String idStr) {
		logger.debug("删除产品");
		if(StringUtils.isBlank(idStr)) return ;
		String[] arrId = idStr.split(",");
		for(String id : arrId){
			if(!StringUtils.isBlank(id)){
				getHibernateTemplate().delete(getHibernateTemplate().load(Product.class, Integer.valueOf(id)));				
			}
		}
	}

	@SuppressWarnings("unchecked")
	public Collection<Product> findProductByParameter(Product product) {
		logger.debug("查询产品");
		
		String sql = "from Product where 1=1 ";
		if(product.getOnline() != null && product.getOnline()>0){
			sql += " and online = " + product.getOnline();
		}
		
		if(product.getSeriesId() != null &&  product.getSeriesId() > 0){
			sql += " and seriesId = " + product.getSeriesId();
		}
		
		if(product.getSeriesNameId() != null && product.getSeriesNameId() > 0){
			sql += " and seriesNameId = " + product.getSeriesNameId();
		}
		
		if(StringUtils.isNotBlank(product.getName())){
			sql += " and name like '%" + product.getName() + "%'";
		}
		
		sql += " order by no asc";
			
		return getHibernateTemplate().find(sql);
	}

	public Product load(int id) {
		logger.debug("查询单个产品");
		
		return (Product) getHibernateTemplate().load(Product.class, id);
	}

	public void saveOrUpdateProduct(Product product) {
		logger.debug("增加/修改产品");
		getHibernateTemplate().saveOrUpdate(product);
	}

	@Override
	public int updateOnline(String idStr,int value) {
		final String sql = "update Product set online = " + value + " where id in ('" + idStr.replaceAll(",", "','") + "')" ;
		return getHibernateTemplate().bulkUpdate(sql);
	}

}
